package cn.tedu.mall.order.service.impl;

import cn.tedu.mall.order.mapper.OrderMapper;
import cn.tedu.mall.order.service.IOrderAddService;
import cn.tedu.mall.pojo.order.dto.OrderAddCondition;
import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderAddServiceImpl implements IOrderAddService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void addOrder(OrderAddCondition orderAddCondition) {
        //1. 使用sn查询是否已经有订单
        String sn = orderAddCondition.getSn();
        boolean existsOrder=orderMapper.selectCountBySn(sn);
        if (existsOrder){
            log.error("订单已经存在,sn:{},重复下单",sn);
            return;
        }
        //2. 发送半消息 半消息是不是要发消息?
        //目的是发送一旦成功,购物车消费者,监听消费删除购物车

        //SN 赋值给事务Id
        if (orderAddCondition instanceof OrderAddDTO){
            Message message=
                    //payLoad 底层序列化会变成byte[] 消费端接收,没问题的
                    //但是分布式消息事务回调接收之后,转化是比较麻烦的.
                    MessageBuilder.withPayload(sn)
                            .setHeader("name","localAdd").build();
            //TODO,提供给回调方法使用的SN采用头header的方式携带
            rocketMQTemplate.sendMessageInTransaction(
                    "csmall-tx-cart-delete-topic:localAdd",message,orderAddCondition);
        }else if (orderAddCondition instanceof SeckillOrderAddDTO){
            Message message=
                    //payLoad 底层序列化会变成byte[] 消费端接收,没问题的
                    //但是分布式消息事务回调接收之后,转化是比较麻烦的.
                    MessageBuilder.withPayload(sn)
                            .setHeader("name","seckillAdd").build();
            //TODO,提供给回调方法使用的SN采用头header的方式携带
            rocketMQTemplate.sendMessageInTransaction(
                    "csmall-tx-cart-delete-topic:seckillAdd",message,orderAddCondition);
        }else{
            log.error("订单类型不属于当前业务选型范畴,请检查:{}",orderAddCondition.getClass().getName());
            return;
        }
    }

}


